package org.andao.commons.lucene.interceptor;

import java.lang.reflect.Method;

import org.andao.commons.lucene.annotation.IndexUpdater;
import org.andao.commons.lucene.annotation.LuceneField;
import org.andao.core.support.context.SpringContextHolder;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.support.AopUtils;


/**
 * 全文检索拦截器，拦截method，判断其参数是否带@LuceneField
 * <p>
 * 如:拦截到save(User user); 则检测User实体类中是否有@LuceneField
 * 
 * @author Seewo Software - Vick.liu (liuguanglin@cvte.cn)
 * 
 */
public class IndexUpateInterceptor implements MethodBeforeAdvice, AfterReturningAdvice {

	/**
	 * 判断其参数是否带@LuceneField
	 * <p>
	 * 如:拦截到save(User user);
	 * 则检测User实体类中是否有@LuceneField，如果有，则执行@LuceneField#updater(user);
	 */
	@Override
	@SuppressWarnings("unchecked")
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		for (Object arg : args) {
			LuceneField annotation = (LuceneField) AopUtils.getTargetClass(arg).getAnnotation(LuceneField.class);
			if (null != annotation) {
				// 被标注为LuceneField，需要更新索引
				IndexUpdater updater = (IndexUpdater) SpringContextHolder.getApplicationContext().getBean(annotation.updater().getSimpleName(), annotation.updater());
				updater.update(arg);
			}
		}
	}

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
	}

}
